#include "List.h"

ListNode* ListCreate(LTDataType x)
{
	ListNode* newhead = (ListNode*)malloc(sizeof(ListNode));
	if (newhead == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}

	newhead -> data = x;
	newhead->prev = NULL;
	newhead->next = NULL;

	return newhead;
}

ListNode* LTInit()
{
	ListNode* phead = ListCreate(-1);
	phead->prev = phead;
	phead->next = phead;

	return phead;
}


void ListPrint(ListNode* pHead)
{
	assert(pHead);
	printf("哨兵位 <--> ");
	ListNode* cur = pHead->next;
	
	while (cur != pHead)
	{
		printf("%d <--> ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}


void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);

	ListNode* tail = pHead->prev;

	ListNode* newnode = ListCreate(x);
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = pHead;
	pHead->prev = newnode;
}


void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(pHead->next != pHead);


	ListNode* tail = pHead->prev;
	ListNode* tailPrev = tail->prev;
	free(tail);
	tailPrev->next = pHead;
	pHead->prev = tailPrev;

}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newhead = ListCreate(x);

	newhead->next = pHead->next;
	pHead->next->prev = newhead;
	pHead->next = newhead;
	newhead->prev = pHead;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(pHead->next != pHead);

	ListNode* first = pHead->next;
	ListNode* second = first->next;

	pHead->next = second;
	second->prev = pHead;
	free(first);

	first = NULL;
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);

	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}


void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* posPrev = pos->prev;
	ListNode* newnode = ListCreate(x);

	posPrev->next = newnode;
	newnode->prev = posPrev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);

	ListNode* posPrev = pos->prev;
	ListNode* posNext = pos->next;

	posPrev->next = posNext;
	posNext->prev = posPrev;
	free(pos);
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);

	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(pHead);
}